package cn.interestingshop.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description TODO
 * @Author com.com.hyl
 * @Date 2022/8/25 10:46
 **/
public class MyBatisUtil {
	static SqlSessionFactory factory = null;

	static {
		//1、配置mybatis文件
		String resource ="mybatis-config.xml";
		InputStream is = null;
		try {
			//2、引用
			is = Resources.getResourceAsStream(resource);
			//3、创建SqlSessionFactory
			factory = new SqlSessionFactoryBuilder().build(is);
			//4、打开SqlSession
		//	session = factory.openSession();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static SqlSession getSqlSession(){
		return factory.openSession(false); //关闭自动提交事务
	}

	public static void closeSqlSession(SqlSession sqlSession){
		if(sqlSession != null) {
			sqlSession.close();
		}
	}

}

